<script setup>
import { User, Lock } from '@element-plus/icons-vue'
import { ref, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { userRegisterService, userLoginService } from '@/api/user'
import { useUserStore } from '@/stores'
import { useRouter } from 'vue-router'
const isRegisterPage = ref(false)
// 切换表单，清除表单内容

watch(isRegisterPage, () => {
  formModel.value = {
    username: '',
    password: '',
    repassword: ''
  }
})

// 表单dom
const form = ref({})

// 表单的属性
const formModel = ref({
  username: 'huajiaqi',
  password: '123456',
  repassword: ''
})

// 表单校验规则
const rules = ref({
  username: [
    {
      required: true,
      message: '请输入用户名',
      trigger: 'change'
    },
    {
      min: 6,
      max: 16,
      message: '用户名为6-16位',
      trigger: 'blur'
    }
  ],
  password: [
    {
      required: true,
      message: '请输入密码',
      trigger: 'change'
    },
    {
      pattern: /^\S{6,15}$/,
      message: '密码必须是6-15位的非空字符',
      trigger: 'blur'
    }
  ],
  repassword: [
    {
      required: true,
      message: '请输入密码',
      trigger: 'change'
    },
    {
      pattern: /^\S{6,15}$/,
      message: '密码必须是6-15位的非空字符',
      trigger: 'blur'
    },
    {
      validator: (rule, value, callback) => {
        if (value !== formModel.value.password) {
          callback(new Error('两次输入的密码不一致'))
        } else {
          callback()
        }
      }
    }
  ]
})
// 注册
const register = async () => {
  // 表单整体校验
  await form.value.validate()
  const res = await userRegisterService(formModel.value)
  console.log(res)
  ElMessage.success('注册成功')
  isRegisterPage.value = false
}
const userStore = useUserStore()
const setToken = userStore.setToken
const router = useRouter()
// 登录
const login = async () => {
  // 表单整体校验
  await form.value.validate()
  const res = await userLoginService(formModel.value)
  console.log(res)
  ElMessage.success('登录成功')
  setToken(res.data.token)
  router.replace('/')
}
</script>
<!--
  结构相关
  el-row 表示行，一行分24分
  el-col 表示列
    属性 :span="12" 表示，站一行的12份
    属性 :offset="3" 表示，向右偏移3份，相当于margin-left:3/24%

  el-form 表示表单
  el-form-item 表示表单的一行，一个表单域
  el-input 表单元素，输入框
    :prefix-icon="User" 设置输入框的图像
  el-checkbox 多选框
el-link 超链接，
    :underline="false" 隐藏鼠标悬浮下划线
 -->
<!--
  校验相关
  el-form => ：model="ruleForm" 绑定的是整个form的数据对象
  el-form => :rules="rules" 绑定整个rules规则对象
    rule规则
      required 非空校验
      message 文本提示
      trigger 触发时机 change，blur
      min,max 文本长度的最小值，最大值
      pattern 正则校验

      自定义校验
        (rule,value,callback)
          rule，校验规则相关的信息
          value，所校验的表单元素目前的表单值
          callback，回调函数，无论成功还是失败，都需要callback回调
            调用方式：
              1. callback(),校验成功
              2. callback(new Error('错误信息'))

  表单元素 => v-model="ruleForm.xxx" 给表单元素，绑定form的子属性
  el-form-item => prop配置生效的是那个校验规则，（与rules中的字段要对应）
  -->
<template>
  <div>
    <el-row>
      <el-col :span="12" class="left-bg"></el-col>
      <el-col :span="6" :offset="3" class="right-form">
        <!-- 登录表单 -->
        <el-form
          ref="form"
          :model="formModel"
          :rules="rules"
          size="large"
          autocomplete="off"
          v-if="!isRegisterPage"
        >
          <el-form-item>
            <h1>登录</h1>
          </el-form-item>
          <el-form-item prop="username">
            <el-input
              v-model="formModel.username"
              :prefix-icon="User"
              type="text"
              placeholder="请输入用户名"
            />
          </el-form-item>
          <el-form-item prop="password">
            <el-input
              v-model="formModel.password"
              :prefix-icon="Lock"
              placeholder="请输入密码"
              type="password"
            />
          </el-form-item>
          <el-form-item>
            <div class="flex">
              <el-checkbox label="记住我" size="large" />
              <el-link type="primary" :underline="false">忘记密码?</el-link>
            </div>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" class="button" @click="login">登录</el-button>
          </el-form-item>
          <el-form-item>
            <el-link type="info" :underline="false" @click="isRegisterPage = true">注册</el-link>
          </el-form-item>
        </el-form>

        <!-- 注册表单 -->
        <el-form
          ref="form"
          :model="formModel"
          :rules="rules"
          size="large"
          autocomplete="off"
          v-else
        >
          <el-form-item>
            <h1>注册</h1>
          </el-form-item>
          <el-form-item prop="username">
            <el-input
              v-model="formModel.username"
              type="text"
              :prefix-icon="User"
              placeholder="请输入用户名"
            />
          </el-form-item>
          <el-form-item prop="password">
            <el-input
              v-model="formModel.password"
              type="password"
              :prefix-icon="Lock"
              placeholder="请输入密码"
            />
          </el-form-item>
          <el-form-item prop="repassword">
            <el-input
              v-model="formModel.repassword"
              type="password"
              :prefix-icon="Lock"
              placeholder="请再次输入密码"
            />
          </el-form-item>

          <el-form-item>
            <el-button type="primary" class="button" @click="register">注册</el-button>
          </el-form-item>
          <el-form-item>
            <el-link type="info" :underline="false" @click="isRegisterPage = false">返回</el-link>
          </el-form-item>
        </el-form>
      </el-col>
    </el-row>
  </div>
</template>

<style lang="scss" scoped>
.left-bg {
  height: 100vh;
  background:
    url('/src/assets/logo2.png') no-repeat center / 240px auto,
    url('/src/assets/login_bg.jpg') no-repeat center / cover;
  border-radius: 1vw;
}
.right-form {
  display: flex;
  flex-direction: column;
  justify-content: center;
  user-select: none;
  .button {
    width: 100%;
  }
  .flex {
    width: 100%;
    display: flex;
    justify-content: space-between;
  }
}
</style>
